﻿#include"XQHttpHeadReply.h"

XQHttpHeadReply::XQHttpHeadReply(const QByteArray& data)
	:XQHttpHeadObject(data)
{
	if (data.isEmpty())
		init();
	else
		setData(data);
}

QByteArray XQHttpHeadReply::header_toByteArray() const
{
	return versions_toByteArray() + " " + QByteArray::number(statusCode()) + " " + statusInfo() + "\r\n"+XQHttpHeadObject::header_toByteArray();
}

int XQHttpHeadReply::statusCode() const
{
	return m_statusCode;
}

QByteArray XQHttpHeadReply::statusInfo() const
{
	return m_statusInfo;
}

void XQHttpHeadReply::setData(const QByteArray& data)
{
	QByteArray buff;
	auto nSel=data.indexOf("\r\n\r\n");
	if (nSel != -1)
		buff = data.left(nSel+2);
	else
		buff = data;
	auto list = buff.split('\n');
	if (list.isEmpty())
		return;
	//第一行版本判断
	{
		auto info = list[0].trimmed();
		auto one = info.indexOf(" ");
		if (one != -1)
		{
			setVersions(getVersions(info.left(one)));
			auto two= info.indexOf(" ",one);
			if (one != -1)
			{
				setStatusCode(info.mid(one+1,two-one).toInt());
				setStatusInfo(info.mid(two+1));
			}
		}
	}
	//头部数据
	list.pop_front();
	setHeader(list);
	//内容
	auto content = data.mid(nSel + 4);
	if (content.size() == contentLength())
	{
		m_content = data;
	}
}

void XQHttpHeadReply::setStatusCode(int code)
{
	m_statusCode = code;
}

void XQHttpHeadReply::setStatusInfo(const QByteArray& data)
{
	m_statusInfo = data;
}

void XQHttpHeadReply::clear()
{
	XQHttpHeadObject::clear();
	m_statusInfo.clear();
	m_statusCode = 200;
}

void XQHttpHeadReply::init()
{
	m_header.clear();
	setVersions(Http::HTTP11);
	setStatusCode(200);
	setStatusInfo("OK");
	setHeader("Content-Type", "text/html");
	setHeader("Connection", "Keep-Alive");
}
